package com.spark.gaea.mvc.utils;

import com.google.common.collect.Maps;
import com.spark.gaea.utils.exception.ApiException;
import com.spark.gaea.utils.exception.GaeaAuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@ControllerAdvice(annotations = {RestController.class})
public class MvcExceptionHandler {
	private static final Logger LOG;

	@ExceptionHandler({Exception.class})
	@ResponseBody
	public Object handleException(final Exception exception, final HttpServletResponse response) {
		MvcExceptionHandler.LOG.error(exception.getMessage(), exception);
		final Map map = Maps.newHashMap();
		if (exception instanceof GaeaAuthenticationException) {
			response.setStatus(401);
			map.put("errorCode", 401);
		} else if (exception instanceof ApiException) {
			response.setStatus(432);
			map.put("errorCode", 432);
		} else {
			response.setStatus(500);
			map.put("errorCode", 500);
		}
		map.put("errorText", exception.getMessage());
		return map;
	}

	static {
		LOG = LoggerFactory.getLogger(MvcExceptionHandler.class);
	}
}
